package com.ksyun.campus.metaserver.controller;

import com.ksyun.campus.metaserver.domain.ApiResponse;
import com.ksyun.campus.metaserver.domain.dto.FileBlockInfo;
import com.ksyun.campus.metaserver.services.MetaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("/")
@Slf4j
public class MetaController {

    @Autowired
    MetaService metaService;

    //获取状态
    @GetMapping("stats")
    public ApiResponse stats(@RequestHeader(required = false) String fileSystem,@RequestParam String path){
        String fileStatus = metaService.getFileStatus(fileSystem, path);
        if(fileStatus==null){
            return new ApiResponse(500,"fail",null);
        }
        return new ApiResponse<>(200,"OK",fileStatus);
    }


    @GetMapping("create")
    public ApiResponse createFile(@RequestHeader(required = false) String fileSystem,@RequestParam String path){
        // 将这个文件的数据存到本地或者zk
        return metaService.createFile(fileSystem,path);
    }

    @GetMapping("mkdir")
    public ApiResponse mkdir(@RequestHeader(required = false) String fileSystem, @RequestParam String path){
        return metaService.mkdir(fileSystem,path);
    }

    @RequestMapping("listdir")
    public ApiResponse listdir(@RequestHeader(required = false) String fileSystem,@RequestParam String path){
        return metaService.listdir(fileSystem,path);
    }

    @GetMapping("delete")
    public ApiResponse delete(@RequestHeader(required = false) String fileSystem, @RequestParam String path){
        return metaService.delete(fileSystem,path);
    }

    /**
     * 保存文件写入成功后的元数据信息，包括文件path、size、三副本信息等
     * @param fileSystem 磁盘
     *
     * @return
     */
    @PostMapping("write")
    public ApiResponse commitWrite(@RequestHeader(required = false) String fileSystem,
                                      @RequestBody FileBlockInfo fileBlockInfo){

        try {
            boolean write = metaService.write(fileSystem, fileBlockInfo);
            return new ApiResponse(200,"OK",write);
        } catch (Exception e) {
            return new ApiResponse(500,"error","出现异常");
        }
    }

    /**
     * 根据文件path查询三副本的位置，返回客户端具体ds、文件分块信息
     * @param fileSystem
     * @param path
     * @return
     */
    @GetMapping("open")
    public ApiResponse open(@RequestHeader String fileSystem,@RequestParam String path){
        return metaService.open(fileSystem, path);
    }

    /**
     * 关闭退出进程
     */
    @RequestMapping("shutdown")
    public void shutdownServer(){
        System.exit(-1);
    }

}
